package com.manor.paradise.activity

import android.content.Intent
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.kongzue.dialog.v3.CustomDialog
import com.lxj.xpopup.core.BasePopupView
import com.manor.common.activity.AbsActivity
import com.manor.common.em.AuthType
import com.manor.common.http.JHttpCallback
import com.manor.common.utils.*
import com.manor.paradise.R
import com.manor.paradise.adapter.AlreadyFeedAnimalAdapter
import com.manor.paradise.bean.MyHireBean
import com.manor.paradise.bean.ParadiseInfoBean
import com.manor.paradise.http.ElvesHttpUtil
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.include_animal_location.*
import kotlinx.android.synthetic.main.lyb_activity_active_index.*
import kotlinx.android.synthetic.main.lyb_activity_tm_park.*
import kotlinx.android.synthetic.main.lyb_dialog_has_no_jz.view.*

/**
 * 淘米乐园首页
 */
@Route(path = RouteUtil.ROUTER_TM_PARADISE_NEW_LYB)
class LybTmParkActivity : AbsActivity(){
    private val mAnimalIvList = arrayListOf<ImageView>()
    private val mList = arrayListOf<MyHireBean.RecordsBean>()
    private val mAdapter by lazy { AlreadyFeedAnimalAdapter(mList) }
    private val maxRetry = 3
    private var curRetry = 0
    private var mXpopup: BasePopupView? = null
    internal var pageNum = 1

    /**
     * 是否有卷轴，是否有资格做任务
     */
    private var mHasJz = true

    override fun getLayoutId() = R.layout.lyb_activity_tm_park

    override fun main() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.transparent)
                .titleBar(tagLayout1)
                .statusBarDarkFont(false)
                .init()
        mAnimalIvList.add(m1AnimalIv)
        mAnimalIvList.add(m2AnimalIv)
        mAnimalIvList.add(m3AnimalIv)
        mAnimalIvList.add(m4AnimalIv)
        mAnimalIvList.add(m5AnimalIv)
        mAnimalIvList.add(m6AnimalIv)
        mAnimalIvList.add(m7AnimalIv)
        mAnimalIvList.add(m8AnimalIv)
        mAnimalIvList.add(m9AnimalIv)
        mAnimalIvList.add(m10AnimalIv)
        mAnimalIvList.add(m11AnimalIv)
        mAnimalIvList.add(m12AnimalIv)
        mAnimalIvList.add(m13AnimalIv)
        mAnimalIvList.add(m14AnimalIv)
        mAnimalIvList.add(m15AnimalIv)
        mAnimalIvList.add(m16AnimalIv)
        mAnimalIvList.add(m17AnimalIv)
        mAnimalIvList.add(m18AnimalIv)
        mAlreadyFeedRv.adapter = mAdapter
        initView()
    }

    override fun onResume() {
        super.onResume()
        getMode()
        setData()
    }

    private fun initView() {
        setClick(mFinishIv, mHowPlayIv, mTmParadiseTv, mTmMarketTv, mMyFarmIv, mBreedingRecordsIv, mFeedAnimalIv, mFeedMoreIv)
        mAlreadyFeedSrl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum++
                setData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                setData()
            }
        })
    }


    override fun onClick(v: View?) {
        if (ClickUtil.canClick())
            when (v?.id) {
                R.id.mFinishIv -> {
                    ActivityUtils.finishActivity(this)
                }
                R.id.mHowPlayIv -> {//玩法介绍
                    startActivity(Intent(this, LybHowPlayActivity::class.java))
                }
                R.id.mTmParadiseTv -> {//淘米乐园
                    WebTaskActivity.forward(true)
                }
                R.id.mMyFarmIv -> {//我的庄园
                    ActivityUtils.startActivity(LybMyFarmActivity::class.java)
                }
                R.id.mTmMarketTv -> {//淘米集市
                    // 现金任务，跳web
                    WebTaskActivity.forward(false)
                }
                R.id.mBreedingRecordsIv -> {//养殖记录
                    startActivity(Intent(this, LybFeedHistoryActivity::class.java))
                }
                R.id.mFeedAnimalIv -> {//喂动物
                    if (mHasJz){
                        startActivity(Intent(this, LybDoTaskActivity::class.java))
                    }else{
                        CustomDialog.show(this as AppCompatActivity, R.layout.lyb_dialog_has_no_jz) { dialog, v ->
                            ClickUtils.applySingleDebouncing(v.dialogCloseIv, 500){
                                dialog.doDismiss()
                            }
                            ClickUtils.applySingleDebouncing(v.dialogIKnowBtn, 500){
                                ActivityUtils.startActivity(LybFeedMoreAnimalsActivity::class.java)
                                dialog.doDismiss()
                            }
                        }
                    }
                }
                R.id.mFeedMoreIv -> {//养殖更多
                    ActivityUtils.startActivity(LybFeedMoreAnimalsActivity::class.java)
                }
            }
    }
    var jlLyEnable = ""
    private var isJinru = false
    private fun getMode() {
        ElvesHttpUtil.getParadiseInfo(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    if (curRetry >= maxRetry) {
                        finish()
                    } else {
                        curRetry++
                        getMode()
                        ToastUtil.show(msg)
                        return
                    }
                }
                dismissWaitingDialog()
                var paradiseInfoBean: ParadiseInfoBean = GsonUtil.gsonToBean(info, ParadiseInfoBean::class.java)
                jlLyEnable = paradiseInfoBean.jlLyEnable

                SpUtil.getInstance().setBooleanValue(SpUtil.FRIRYLAND_BGETSPIRIT, paradiseInfoBean.bgetSpirit)

                if (!isActDestroy(this@LybTmParkActivity)){
                    GlideUtil.loadImage(paradiseInfoBean.avatar, mParadiseAvatarIv, 40, 40)
                }
                mRiseCountTv.content(paradiseInfoBean.crystalOre)
                when (paradiseInfoBean.star) {
                    -1 -> {
                        mUserLevelTv.text = "无等级"
                        mUserLevelIv.setBackgroundResource(R.drawable.star_no)
                    }
                    0 -> {
                        mUserLevelTv.text = "一星农场主"
                        mUserLevelIv.setBackgroundResource(R.drawable.star1_lighten_b)
                    }
                    1 -> {
                        mUserLevelTv.text = "二星农场主"
                        mUserLevelIv.setBackgroundResource(R.drawable.star2_lighten_b)
                    }
                    2 -> {
                        mUserLevelTv.text = "三星农场主"
                        mUserLevelIv.setBackgroundResource(R.drawable.star3_lighten_b)
                    }
                    3 -> {
                        mUserLevelTv.text = "四星农场主"
                        mUserLevelIv.setBackgroundResource(R.drawable.star4_lighten_b)
                    }
                }
                tvConfirm.setGone(true)
                tvDismiss.text = "取消"

                if (paradiseInfoBean.isAuth == 1) {
                    isJinru = true
                    flAuth.visibility = View.GONE
                } else {
                    flAuth.visibility = View.VISIBLE
                    flAuth.setOnClickListener {}


                    im_close.setOnClickListener { finish() }
                    tv_gz.setOnClickListener { RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.VIP_EXPERIENCE) }
                    tv_rz.setOnClickListener {
                        if (ClickUtil.canClick(1500))
                            setCamera()
                    }
                    tvConfirm.setOnClickListener { RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.VIP_EXPERIENCE) }
                    tvDismiss.setOnClickListener {
                        ActivityUtils.finishActivity(this@LybTmParkActivity)
                    }
                }
            }

            override fun onError() {
                super.onError()
                if (curRetry >= maxRetry) {
                    ToastUtil.show("暂时无法进入淘米庄园，请稍后重试")
                    finish()
                } else {
                    curRetry++
                    getMode()
                }
            }
        })
    }


    private fun setCamera() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA)//相机
                .onGranted {
                    RouteUtil.forwardFaceExp(AuthType.TYPE_AUTH)
                    mXpopup?.dismiss()
                }
                .onDenied { data ->
                    Toast.makeText(this, resources.getString(R.string.permissions_camera),
                            Toast.LENGTH_SHORT).show()
                    if (AndPermission.hasAlwaysDeniedPermission(this, data)) {
                        showSettingDialog(this,
                                resources.getString(R.string.permissions_camera), 0)
                    } else {
                        setCamera()
                    }
                }
                .start()
    }

    fun setData() {
        ElvesHttpUtil.getMyhire(pageNum, object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                val shopListBean: MyHireBean = GsonUtil.gsonToBean<MyHireBean>(info, MyHireBean::class.java)
                KLog.e("json", shopListBean)
                if (pageNum == 1) {
                    mAdapter.setNewInstance(shopListBean.records)
                    mAlreadyFeedSrl?.finishRefresh()
                    if (shopListBean.records.size == 0) {
                        mEmptyView?.showNull()
                        mHasJz = false
                    } else {
                        mHasJz = true
                        var entity: MyHireBean.RecordsBean
                        for (i in shopListBean.records.indices){
                            if (i <= 17){
                                entity = shopListBean.records[i]
                                when(entity.spiritId){
                                    1 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_xiong)) }
                                    2 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_ji)) }
                                    3 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_gou)) }
                                    4 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_zhu)) }
                                    5 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_yang)) }
                                    6 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_niu)) }
                                    7 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_hu)) }
                                    8 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_feng)) }
                                    9 ->{ mAnimalIvList[i].setImageDrawable(ContextCompat.getDrawable(this@LybTmParkActivity, R.drawable.jz_long)) }
                                }
                            }
                        }
                        mEmptyView?.visibility = View.GONE
                    }
                } else {
                    mAdapter.addData(shopListBean.records)
                    mAlreadyFeedSrl?.finishLoadMore()
                }
            }
        })
    }
}
